package com.jf.yytgd.web;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalTime;

/**
 * Created with IntelliJ IDEA
 * Description: 验证码控制层
 * User:22954
 * Date:2025-01-15
 * Time:9:25
 */
@Controller
public class KaptchaController {
    @Resource
    private DefaultKaptcha kaptcha;

    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response, HttpSession httpSession) throws IOException {
        String codeText = kaptcha.createText();
        BufferedImage image = kaptcha.createImage(codeText);

        httpSession.setAttribute(Constants.KAPTCHA_SESSION_KEY, codeText);
        httpSession.setAttribute(Constants.KAPTCHA_SESSION_DATE, LocalTime.now());

        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }
}
